﻿using MLSMooc.BO;
using MLSMooc.Service.Interface.Feedback;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using MLSMooc.Helper;
using Dapper;

namespace MLSMooc.Service.Implement.Feedback
{
   public class FeedbackServiceImpl :IFeedbackService
    {
        private static FeedbackServiceImpl instance = new FeedbackServiceImpl();

        private FeedbackServiceImpl() { }
        public static FeedbackServiceImpl Getinstance() => instance;

        public async Task<int> InsertFeedback(FeedbackBO data) 
        {
            using (SqlConnection conn=new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder();
             sql.Append($@"insert into Mooc_Project_Feedback values(@Fee_Content,@ProId,@AdminId,@Grade,getdate(),getdate(),0)");
                var res = await conn.ExecuteAsync(sql.ToString(), new { Fee_Content = data.Fee_Content, ProId = data.ProId, AdminId = data.AdminId, Grade = data.Grade });
                if (res>0)
                {
                    StringBuilder sql1 = new StringBuilder();
                     sql1.Append($@"update Mooc_Project set Pro_CradeNum=(select count(*) from Mooc_Project_Feedback where ProId=@ProId) ,Pro_GradeAvg=(select avg(Grade) from Mooc_Project_Feedback where ProId=@ProId) where Id=@ProId");
                    var res1 = await conn.ExecuteAsync(sql1.ToString(), new { ProId = data.ProId });
                    return res1;
                }
                else
                {
                    return 0;
                }
                
            }
        }

        public async Task<int> DeleteFeedback(int id)
        {
            
            using (SqlConnection conn=new SqlConnection(SalesSysSqlHelper.connectionString))
            {
                StringBuilder sql = new StringBuilder($@"update Mooc_Project_Feedback set isDelete=1 where Id=@id");
                var res = await conn.ExecuteAsync(sql.ToString(),new { id=id});
                return res;
            }
        }
    }
}
